package com.cqjtu.store.cart.service.impl;

import com.cqjtu.store.address.mapper.AddressMapper;
import com.cqjtu.store.address.pojo.entity.Address;
import com.cqjtu.store.cart.mapper.CartMapper;
import com.cqjtu.store.cart.pojo.dto.*;
import com.cqjtu.store.cart.pojo.entity.Cart;
import com.cqjtu.store.cart.pojo.vo.CartVO;
import com.cqjtu.store.cart.pojo.vo.CountVO;
import com.cqjtu.store.cart.service.CartService;
import com.cqjtu.store.common.Constants;
import com.cqjtu.store.common.R;
import com.cqjtu.store.common.ServiceCode;
import com.cqjtu.store.common.ServiceException;
import com.cqjtu.store.order.mapper.OrderItemMapper;
import com.cqjtu.store.order.mapper.OrderMapper;
import com.cqjtu.store.order.pojo.entity.Order;
import com.cqjtu.store.order.pojo.entity.OrderItem;
import com.cqjtu.store.product.mapper.ProductMapper;
import com.cqjtu.store.product.pojo.entity.Product;
import com.cqjtu.store.user.pojo.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class) // 事务, 出现任何异常都回滚
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;

    @Autowired
    ProductMapper productMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    AddressMapper addressMapper;

    @Override
    public List<CartVO> getCartList(Integer[] selectedIds,UserLoginVO userLoginVO) {
        List<CartVO> cartList = cartMapper.getCartList(selectedIds, userLoginVO.getId());
        if(cartList == null){
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,"购物车没有添加商品");
        }
        return cartList;
    }

    /**
     * 更新购物车商品数量
     *
     * @param id     购物车id
     * @param flag   1:增加 2:减少
     * @param userId 用户id
     * @return
     */
    @Override
    public R updateCartNumById(Integer id, Integer flag, Integer userId) {
        if (id == null || flag == null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "更新数量错误");
        }
        cartMapper.updateCartNumById(id, flag, userId);
        return R.ok();
    }

    /**
     * 删除购物车商品
     *
     * @param id          购物车id
     * @param userLoginVO 用户id
     */
    @Override
    public void delete(Integer id, UserLoginVO userLoginVO) {
        // 判断购物车是否存在商品
        Cart cart = cartMapper.getById(id);
        if (cart == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "商品不存在");
        }
        //判断该商品是否存在该用户的购物车
        if (cart.getUserId() != userLoginVO.getId()) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "你没有权限删除该商品");
        }

        //删除
        int result = cartMapper.delete(id);
        if (result == 0) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "购物车的商品不存在");
        }
    }

    /**
     * 删除购物车多条商品
     *
     * @param cartDDTOs
     * @param userLoginVO
     */
    @Override
    public void deleteMore(CartDeletesDTO[] cartDDTOs, UserLoginVO userLoginVO) {
        if (cartDDTOs.length == 0) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "没有选择商品");
        }
        for (int i = 0; i < cartDDTOs.length; i++) {
            Cart cart = cartMapper.getById(cartDDTOs[i].getIds());
            //根据商品id删除购物车商品
            /*Cart cart = cartMapper.getByPId(cartDDTOs[i].getIds());*/
            if (!cart.getUserId().equals(userLoginVO.getId())) {
                throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "你没有权限删除该商品");
            }
        }
        for (int i = 0; i < cartDDTOs.length; i++) {
            int result = cartMapper.deleteMore(cartDDTOs[i].getIds());
            if (result == 0) {
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "购物车的商品不存在");
            }
        }
    }

    /**
     * 清空购物车
     *
     * @param userLoginVO
     */

    @Override
    public void clear(UserLoginVO userLoginVO) {
        int result = cartMapper.clear(userLoginVO.getId());
        if (result == 0) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "购物车的商品不存在");
        }
    }

    @Override
    public void countCartList(CountDTO countDTO, UserLoginVO userLoginVO) {
        List<Integer> ids = countDTO.getIds();
        if (ids == null || ids.size() == 0) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "没有选择结算商品，结算无效");
        }

        Address address = addressMapper.getById(countDTO.getAddressId());
        Order order = new Order();
        order.setUserId(userLoginVO.getId());
        order.setRecvName(address.getName());
        order.setRecvPhone(address.getPhone());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvAddress(address.getAddress());
        order.setStatus(Constants.DEFAULT_ORDER_STATUS);
//        order.setTotalPrice();
        order.setOrderTime(new Date());
        order.setCreatedTime(new Date());
//        order.setPayTime();
        order.setCreatedUser(userLoginVO.getUsername());
        order.setModifiedUser(userLoginVO.getUsername());
        order.setModifiedTime(new Date());
        int orderInsert = orderMapper.insert(order);
        if(orderInsert == 0){
            throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "新增订单失败！");
        }

        Long totalPrice = Long.valueOf(0);
        for (Integer id : ids) {
            Cart cart = cartMapper.getById(id);
            if(cart == null){
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "该购物车物品不存在");
            }
            if(cart.getUserId() != userLoginVO.getId()){
                throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "无操作权限");
            }

            Product product = productMapper.getById(cart.getProductId());
            if (product == null) {
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "购买的商品不存在");
            }
            if(product.getNum() < cart.getNum()){
                throw new ServiceException(ServiceCode.ERR_CONFLICT, "商品库存不足");
            }
            int productNumUpdate = productMapper.updateProductNum(cart.getProductId(), cart.getNum());
            if(productNumUpdate == 0){
                throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "商品库存更新失败！");
            }

            totalPrice += cart.getPrice() * cart.getNum();

            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(cart.getProductId());
            orderItem.setNum(cart.getNum());
            orderItem.setPrice(cart.getPrice());
            orderItem.setImage(product.getImage());
            orderItem.setTitle(product.getTitle());
            orderItem.setCreatedUser(userLoginVO.getUsername());
            orderItem.setCreatedTime(new Date());
            orderItem.setModifiedUser(userLoginVO.getUsername());
            orderItem.setModifiedTime(new Date());
            int orderItemInsert = orderItemMapper.insert(orderItem);
            if(orderItemInsert == 0){
                throw new ServiceException(ServiceCode.ERR_SAVE_FAILED, "新增订单物品失败！");
            }

            int cartDelete = cartMapper.delete(id);
            if(cartDelete==0){
                throw new ServiceException(ServiceCode.ERR_DELETE_FAILED, "删除购物车物品失败！");
            }
        }
        order.setTotalPrice(totalPrice);
        int orderResult = orderMapper.updateByPrimaryKey(order);
        if(orderResult == 0){
            throw new ServiceException(ServiceCode.ERR_UPDATE_FAILED, "订单更新失败！");
        }
    }

    /**
     * 添加购物车
     *
     * @param cartInsertDTO
     * @param userLoginVO
     */
    @Override
    public void insert(CartInsertDTO cartInsertDTO, UserLoginVO userLoginVO) {
        if (cartInsertDTO.getUserId() != userLoginVO.getId()) {
            throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "没有操作权限，不能添加商品");
        }
        // 查询商品信息
        Product product = cartMapper.getProductById(cartInsertDTO.getProductId());
        if (product == null) {
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, "商品不存在");
        }
        Cart cart = cartMapper.getByPId(cartInsertDTO.getProductId(), cartInsertDTO.getUserId());
        if (cart != null) {
            throw new ServiceException(ServiceCode.ERR_EXISTS, "商品已经存在购物车");
        }
        if (cartInsertDTO.getNum() <= 0) {
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "商品数量不能小于0");
        }
        if (cartInsertDTO.getNum() > product.getNum()) {
            throw new ServiceException(ServiceCode.ERR_CONFLICT, "商品库存不足");
        }
        // 查询创建者名字
        cartInsertDTO.setCreatedUser(userLoginVO.getUsername());
        cartInsertDTO.setModifiedUser(userLoginVO.getUsername());
        cartInsertDTO.setPrice(product.getPrice());
        System.out.println("cartInsertDTO:"+cartInsertDTO);
        cartMapper.insert(cartInsertDTO);
    }

    @Override
    public void removeByIds(Integer[] ids, UserLoginVO userLoginVO) {
        // 判断当前用户是否有权限删除
        for (Integer id : ids) {
            Cart cart = cartMapper.getById(id);
            if (!cart.getUserId().equals(userLoginVO.getId())) {
                throw new ServiceException(ServiceCode.ERR_FORBIDDEN, "你没有权限删除该商品");
            }
        }
    }
}
